package com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.topic;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.StringUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpActivity;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.di.component.DaggerDynamicComponent;
import com.kaiwukj.android.ufamily.di.module.DynamicModule;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.TopicResult;
import com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.DynamicContract;
import com.kaiwukj.android.ufamily.mvp.ui.page.home.message.ChatActivity;
import com.kaiwukj.android.ufamily.mvp.ui.widget.discussion.DiscussionAvatarView;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterUrlKt.TopicIndexUrl)
public class DynamicTopicActivity extends BaseMvpActivity<TopicPresenter> implements DynamicContract.TopicView {

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.iv_topic)
    ImageView ivTopic;
    @BindView(R.id.tv_title_expand)
    TextView tvTitleExpand;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_hot_expand)
    TextView tvHotExpand;

    @BindView(R.id.tv_topic_person_num)
    TextView tvJoinNum;
    @BindView(R.id.pv_heads)
    DiscussionAvatarView pvHeads;

    @BindView(R.id.tabs)
    TabLayout tabs;
    @BindView(R.id.vp_content)
    ViewPager2 vpContent;

    @Autowired
    int topicId;

    private TopicResult result;

    @OnClick({R.id.container_back, R.id.container_back_expand})
    void backToUp() {
        onBackPressedSupport();
    }

    @OnClick({R.id.btn_chat, R.id.btn_chat_expand})
    void chatToRoom() {
        if (result == null || StringUtils.isEmpty(result.getTopicGroupId())) {
            showMessage("群聊信息获取失败");
            return;
        }
        mPresenter.joinGroup(result.getTopicGroupId());

    }


    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        super.setupActivityComponent(appComponent);
        DaggerDynamicComponent.builder()
                .appComponent(appComponent)
                .dynamicModule(new DynamicModule(this))
                .build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        QMUIStatusBarHelper.translucent(this);
        QMUIStatusBarHelper.setStatusBarLightMode(this);
        ARouter.getInstance().inject(this);
        return R.layout.activity_dynamic_topic;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

        refreshLayout.setEnableLoadMore(false);

        appBarLayout.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
            //appBarLayout.setExpanded();
            int minHeight = appBarLayout.getMinimumHeightForVisibleOverlappingContent();
            if (minHeight < Math.abs(verticalOffset) - BarUtils.getStatusBarHeight()) {
                toolbar.setVisibility(View.VISIBLE);
            } else {
                toolbar.setVisibility(View.GONE);
            }

        });

        List<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(DynamicFragment.newInstance(0, topicId));
        fragmentList.add(DynamicFragment.newInstance(1, topicId));

        List<String> titles = new ArrayList<>();
        titles.add("全部");
        titles.add("最热");

        refreshLayout.setOnRefreshListener(refreshLayout -> {
            mPresenter.getTopicById(topicId);
            ((DynamicFragment) fragmentList.get(vpContent.getCurrentItem())).refreshData();
        });

        // vpContent.get

        vpContent.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return fragmentList.get(position);
            }

            @Override
            public int getItemCount() {
                return fragmentList.size();
            }
        });

        new TabLayoutMediator(tabs, vpContent, (tab, position) ->
                tab.setText(titles.get(position)))
                .attach();

    }

    @Override
    protected void initData(Bundle savedInstanceState) {

        //   "http://jylqntest.kaiwumace.com/icon_20200323161220567.jpg", "userId": 2…},
        //  {"headImg": "http://jylqntest.kaiwumace.com/icon_20191030184103972.jpg", "userId": 1…},
        // {"headImg": "http://jylqntest.kaiwumace.com/1572335620000_dj8tj4XXWJ0wCHl2.jpg"

     /*   ArrayList<String> headList = new ArrayList<>();
        headList.add("http://jylqntest.kaiwumace.com/icon_20200323161220567.jpg");
        headList.add("http://jylqntest.kaiwumace.com/icon_20191030184103972.jpg");
        headList.add("http://jylqntest.kaiwumace.com/1572335620000_dj8tj4XXWJ0wCHl2.jpg");
        pvHeads.initDatas(headList);
*/
        mPresenter.getTopicById(topicId);
        showLoading();
    }

    @Override
    public void onFetchTopic(List<TopicResult> results) {

    }

    @Override
    public void onTopicAdd(Integer topicId) {

    }

    @Override
    public void onGetTopic(TopicResult result) {
        this.result = result;
        hideLoading();
        refreshLayout.finishRefresh();
        tvTitle.setText(result.getTopicTitle());
        tvTitleExpand.setText(result.getTopicTitle());
        tvHotExpand.setText(String.format("%s条讨论", 9527));
        tvJoinNum.setText(String.format("%s人参与话题", result.getJoinTopicNum()));
        if (result.getHeadList() != null && result.getHeadList().size() > 0) {
            pvHeads.initDatas((ArrayList<String>) result.getHeadList());
        }

        //String bgImg = "https://c-ssl.duitang.com/uploads/item/202004/22/20200422225808_ceqvp.jpg";

        Glide.with(this)
                .asBitmap()
                .load(result.getTopicImg())
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(ivTopic);
    }

    @Override
    public void onTopicGroupJoin(String hxGroupId) {
        if (StringUtils.isEmpty(hxGroupId)) {
            showMessage("群聊信息获取失败");
            return;
        }
       /* Intent intent = new Intent(this, ChatActivity.class);
        intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_GROUP);
        intent.putExtra(Constant.EXTRA_GROUP_TYPE, 0);
        intent.putExtra(Constant.EXTRA_USER_ID, result.getTopicGroupId());
        intent.putExtra(Constant.EXTRA_USER_NAME, String.format("#%s", result.getTopicTitle()));
        startActivity(intent);*/
        ChatActivity.startGroupChat(this, result.getId(), result.getTopicGroupId(), String.format("#%s", result.getTopicTitle()), result.getTopicImg());
    }
}
